namespace nu
{
    using System;
    using System.Collections.Generic;
    using Castle.MicroKernel;
    using Commands;
    using Exceptions;

    public class CommandRegistry : ICommandRegistry
    {
        private readonly Dictionary<string, ICommand> _commands;

        public CommandRegistry()
        {
            _commands = new Dictionary<string, ICommand>();
        }

        public ICommand FindCommand(string commandKey)
        {
            if(string.IsNullOrEmpty(commandKey))
            {
                return null;
            }

            try
            {
                return _commands[commandKey.ToLower()];
            }
            catch(KeyNotFoundException)
            {
                throw new PackageException("There is no command with the name " + commandKey);
            }
        }

        public void Intialize()
        {
            string alias = "init-error";
            string commandName = "init-error";

            foreach(IHandler handler in IoC.Container.Kernel.GetAssignableHandlers(typeof(ICommand)))
            {
                try
                {
                    ICommand cmd = (ICommand)handler.Resolve(CreationContext.Empty);
                    alias = GetAlias(cmd);
                    commandName = cmd.GetType().Name;
                    _commands.Add(alias, cmd);
                }
                catch(ArgumentException ex)
                {
                    throw new DuplicateAliasException(string.Format("Duplicate alias was {0} for command {1}", alias, commandName), ex);
                }
            }
        }

        //this should probably be extracted -dru
        private string GetAlias(ICommand cmd)
        {
            if(cmd is AliasCommand) //this is horrible code. how can i refactor
            {
                return ((AliasCommand)cmd).Alias.ToLower();
            }
            else
            {
                return cmd.GetType().Name.Replace("Command", "").ToLower();
            }
        }
    }
}